package com.map_project;

import java.util.StringTokenizer;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;

import android.database.sqlite.SQLiteDatabase;

public class UpdateDatabase extends Activity {
	//private ProgressDialog progressDialog;

		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
				 
			 
		//progressDialog = ProgressDialog.show(this, "Please wait....", "Updating database");
			
			 Thread downloadThread = new Thread() {                     
			 public void run() {   
				 try {

			    	SQLiteDatabase db = openOrCreateDatabase("Geopoints_db",MODE_PRIVATE,null);
					db.execSQL("DROP TABLE IF EXISTS Geopoints");
					db.execSQL("CREATE TABLE IF NOT EXISTS Geopoints (location VARCHAR, address VARCHAR,latitude FLOAT ,longitude FLOAT);");
					 
					Document doc = Jsoup.connect("http://www.vodafone.is/internet/heitirreitir/kort").get();
			        
					Elements list = doc.select(".agent-list");
					Elements items = list.select(".agent-item");
			        
					for (Element item: items){
						Element name = item.select(".agent-name").first();
						Element address = item.select(".agent-address").first();
			    	  		    	  
						Element geopoints = item.select(".agent-loc").first();
		    	 
						String namedb = name.text().toString();
					//	Log.d("name",namedb);
			    	  

			       	  	String addressdb = address.text().toString();
			       	  
				       	  int GeopointLength = 13;
				       	  if(geopoints.text().length() < GeopointLength){
				       		continue;  
				       	  }else{
					    	  StringTokenizer geop = new StringTokenizer(geopoints.text(), ",");
					 //   	  Log.d("geo",geopoints.text());
					    	 
					    	  String lat = geop.nextToken();
	  
					    	//  Log.d("lat",lat);
					     	  String lng = geop.nextToken();
					     	 // Log.d("lng",lng);
					 	       
					     	  double latNum = Double.parseDouble(lat);
					     	  double lngNum = Double.parseDouble(lng);
					     	
					     	  int lat2 = (int) (latNum * 1E6);
					    	  int lng2 = (int) (lngNum * 1E6);
					    	 
					    	  db.execSQL("INSERT INTO Geopoints VALUES ('"+namedb+"','"+addressdb+"','"+lat2+"','"+ lng2+"');"); 
					    	 
				       	  }    
					}
			//		progressDialog.dismiss();
					
					
			    }catch (Exception e) {
			    	e.printStackTrace();
			    }
				 
				
			   
			 }
			
			 
		
			 
			 
		};                                                         
		downloadThread.start(); 
			

			  // finish();
			   
	 }
	 
	 
	 
	
}